package com.superhero.miniprogram.security;


import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;


public class UserUtil {

    public static JwtAuthUser getUser() {
        Object principal = UserUtil.getPrincipal();
        if (!(principal instanceof JwtAuthUser)) {
            throw new RuntimeException("获取用户信息失败");
        }
        return (JwtAuthUser) principal;
    }

    public static Integer getUserRole() {
        JwtAuthUser user = UserUtil.getUser();
        return user.getRole();
    }

    public static Integer getUserId() {
        JwtAuthUser user = UserUtil.getUser();
        return user.getId();
    }

    public static String getUserUsername() {
        JwtAuthUser user = UserUtil.getUser();
        return user.getUsername();
    }

    private static Object getPrincipal() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new RuntimeException("请先登录");
        }
        return authentication.getPrincipal();
    }
}
